<template>
  <div class="server-monitor-container">
    <!-- 骨架屏加载状态 -->
    <div v-if="loading && !serverInfo" class="skeleton-container">
      <div class="dashboard-grid">
        <div class="grid-column">
          <el-skeleton animated>
            <template #template>
              <el-skeleton-item variant="text" style="width: 100%" />
              <el-skeleton-item variant="text" style="width: 60%" />
            </template>
          </el-skeleton>
          <el-skeleton animated>
            <template #template>
              <el-skeleton-item variant="rect" style="width: 100%; height: 120px" />
            </template>
          </el-skeleton>
          <el-skeleton animated>
            <template #template>
              <el-skeleton-item variant="rect" style="width: 100%; height: 120px" />
            </template>
          </el-skeleton>
          <el-skeleton animated>
            <template #template>
              <el-skeleton-item variant="rect" style="width: 100%; height: 100px" />
            </template>
          </el-skeleton>
        </div>
        <div class="grid-column">
          <el-skeleton animated>
            <template #template>
              <el-skeleton-item variant="rect" style="width: 100%; height: 200px" />
            </template>
          </el-skeleton>
          <el-skeleton animated>
            <template #template>
              <el-skeleton-item variant="rect" style="width: 100%; height: 150px" />
            </template>
          </el-skeleton>
        </div>
      </div>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <el-empty :image-size="100" description="服务器信息获取失败">
        <template #extra>
          <el-button type="primary" @click="retryFetch">重新加载</el-button>
        </template>
      </el-empty>
    </div>

    <!-- 正常内容 -->
    <div v-else-if="serverInfo" class="dashboard-grid">
      <!-- Left Column -->
      <div class="grid-column">
        <SystemCard :system="optimizedSystemData" />
        <ResourceCard
          title="CPU"
          :icon="Cpu"
          :used="cpuUsagePercentage"
          :desc="''"
          :color="cpuProgressColor"
          :tooltip="cpuTooltipText"
        />
        <ResourceCard
          title="物理内存"
          :icon="DataLine"
          :used="memoryUsagePercentage"
          :desc="memoryDescText"
          :color="memoryProgressColor"
        />
        <DbCard :db="optimizedDbData" />
      </div>

      <!-- Right Column -->
      <div class="grid-column">
        <JvmCard :jvm="optimizedJvmData" />
        <DiskCard :disks="optimizedDisksData" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, nextTick, defineAsyncComponent } from 'vue'
import { ElSkeleton, ElEmpty, ElButton } from 'element-plus'
import { Cpu, DataLine } from '@element-plus/icons-vue'
import { getServerInfo } from '@/api/monitor'
import { formatFileSize } from '@/utils/format'

// 异步组件 - 懒加载
const ResourceCard = defineAsyncComponent(() => import('./components/ResourceCard.vue'))
const SystemCard = defineAsyncComponent(() => import('./components/SystemCard.vue'))
const DiskCard = defineAsyncComponent(() => import('./components/DiskCard.vue'))
const DbCard = defineAsyncComponent(() => import('./components/DbCard.vue'))
const JvmCard = defineAsyncComponent(() => import('./components/JvmCard.vue'))

// 状态管理
let pollingTimer = null
const serverInfo = ref(null)
const loading = ref(true)
const error = ref(false)
const lastFetchTime = ref(0)

// 防抖函数
const debounce = (func, delay) => {
  let timeoutId
  return (...args) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => func.apply(null, args), delay)
  }
}

// --- 优化后的计算属性 ---
// CPU 相关计算属性（缓存计算结果）
const cpuData = computed(() => serverInfo.value?.cpu || null)
const cpuUsagePercentage = computed(() => {
  if (!cpuData.value) return 0
  return parseFloat((cpuData.value.systemUsage + cpuData.value.userUsage).toFixed(2))
})

const cpuTooltipText = computed(() => {
  if (!cpuData.value) return ''
  const cpu = cpuData.value
  return `核心数: ${cpu.cores} | 系统: ${cpu.systemUsage.toFixed(2)}% | 用户: ${cpu.userUsage.toFixed(2)}% | 空闲: ${cpu.idle.toFixed(2)}%`
})

const cpuProgressColor = computed(() => {
  const percentage = cpuUsagePercentage.value
  if (percentage > 90) return 'var(--el-color-error)'
  if (percentage > 70) return 'var(--el-color-warning)'
  return 'var(--el-color-primary)'
})

// 内存相关计算属性
const memoryData = computed(() => serverInfo.value?.memory || null)
const memoryUsagePercentage = computed(() => {
  if (!memoryData.value?.total) return 0
  return parseFloat(((memoryData.value.used / memoryData.value.total) * 100).toFixed(2))
})

const memoryDescText = computed(() => {
  if (!memoryData.value) return ''
  return `${formatFileSize(memoryData.value.used)} / ${formatFileSize(memoryData.value.total)}`
})

const memoryProgressColor = computed(() => {
  const percentage = memoryUsagePercentage.value
  if (percentage > 90) return 'var(--el-color-error)'
  if (percentage > 70) return 'var(--el-color-warning)'
  return 'var(--el-color-primary)'
})

// 优化的数据传输对象
const optimizedSystemData = computed(() => ({
  hostName: serverInfo.value?.system?.hostName || '',
  osName: serverInfo.value?.system?.osName || '',
  osArch: serverInfo.value?.system?.osArch || '',
}))

const optimizedJvmData = computed(() => ({
  usedMemory: serverInfo.value?.jvm?.usedMemory || 0,
  maxMemory: serverInfo.value?.jvm?.maxMemory || 0,
  uptime: serverInfo.value?.jvm?.uptime || 0,
  threadCount: serverInfo.value?.jvm?.threadCount || 0,
  peakThreadCount: serverInfo.value?.jvm?.peakThreadCount || 0,
  loadedClassCount: serverInfo.value?.jvm?.loadedClassCount || 0,
  gcCount: serverInfo.value?.jvm?.gcCount || 0,
  gcTime: serverInfo.value?.jvm?.gcTime || 0,
}))

const optimizedDbData = computed(() => ({
  activeConnections: serverInfo.value?.db?.activeConnections || 0,
  maxConnections: serverInfo.value?.db?.maxConnections || 0,
  minConnections: serverInfo.value?.db?.minConnections || 0,
  driverVersion: serverInfo.value?.db?.driverVersion || '',
}))

const optimizedDisksData = computed(() => serverInfo.value?.disks || [])

// --- 函数 ---
const fetchServerInfo = async () => {
  const now = Date.now()
  // 防止重复请求（5秒间隔内的重复调用会被忽略）
  if (now - lastFetchTime.value < 4800) {
    return
  }

  lastFetchTime.value = now

  try {
    loading.value = true
    error.value = false

    const data = await getServerInfo()

    // 使用 nextTick 确保动画效果
    await nextTick()

    serverInfo.value = data
    loading.value = false
  } catch (error) {
    console.error('获取服务器信息失败:', error)
    loading.value = false
    error.value = true

    // 错误时不停止轮询，但延长间隔
    if (pollingTimer) {
      clearInterval(pollingTimer)
      pollingTimer = setInterval(fetchServerInfo, 15000) // 错误时延长到15秒
    }
  }
}

// 重试函数
const retryFetch = async () => {
  error.value = false
  await fetchServerInfo()
  // 恢复正常的轮询间隔
  if (pollingTimer) {
    clearInterval(pollingTimer)
    pollingTimer = setInterval(fetchServerInfo, 5000)
  }
}

// 防抖的页面可见性处理
const handleVisibilityChange = debounce(() => {
  if (!document.hidden && serverInfo.value) {
    fetchServerInfo()
  }
}, 1000)

// --- 生命周期钩子 ---
onMounted(async () => {
  // 立即执行一次
  await fetchServerInfo()

  // 设置定时轮询
  pollingTimer = setInterval(fetchServerInfo, 5000)

  // 页面可见性变化时刷新数据
  document.addEventListener('visibilitychange', handleVisibilityChange)
})

onUnmounted(() => {
  if (pollingTimer) {
    clearInterval(pollingTimer)
  }
  document.removeEventListener('visibilitychange', handleVisibilityChange)
})
</script>

<style lang="scss" scoped>
.server-monitor-container {
  padding: 16px;
  min-height: calc(100vh - 120px);

  .dashboard-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 16px;
    animation: fadeIn 0.5s ease-out;
  }

  .grid-column {
    display: grid;
    gap: 16px;
  }

  // 骨架屏样式
  .skeleton-container {
    .dashboard-grid {
      grid-template-columns: repeat(2, minmax(0, 1fr));
      gap: 16px;
    }

    .grid-column {
      display: grid;
      gap: 16px;
    }

    .el-skeleton {
      padding: 16px;
      border-radius: 8px;
      background: white;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    }
  }

  // 错误状态样式
  .error-container {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 400px;

    .el-empty {
      text-align: center;

      :deep(.el-empty__description) {
        color: var(--el-text-color-secondary);
        margin: 16px 0;
      }
    }
  }
}

// 骨架屏动画
@keyframes skeleton-animation {
  0% {
    background-position: -200px 0;
  }
  100% {
    background-position: calc(200px + 100%) 0;
  }
}

:deep(.el-skeleton__item) {
  background: linear-gradient(90deg, #f2f2f2 25%, #e6e6e6 37%, #f2f2f2 63%);
  background-size: 400px 100%;
  animation: skeleton-animation 1.4s ease infinite;
}

// 进场动画
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 卡片悬停效果增强
:deep(.el-card) {
  transition: all 0.3s ease;
  border: 1px solid var(--el-border-color-light);

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
    border-color: var(--el-color-primary-light-7);
  }
}

// 异步组件加载占位
:deep(.component-container) {
  min-height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--el-text-color-secondary);
}

// 响应式布局
@media (max-width: 1200px) {
  .server-monitor-container {
    .dashboard-grid {
      grid-template-columns: 1fr;
    }

    .skeleton-container .dashboard-grid {
      grid-template-columns: 1fr;
    }
  }
}

// 移动端优化
@media (max-width: 768px) {
  .server-monitor-container {
    padding: 12px;

    .dashboard-grid,
    .skeleton-container .dashboard-grid {
      gap: 12px;
    }

    .grid-column {
      gap: 12px;

      :deep(.el-card) {
        margin-bottom: 0;
      }
    }
  }
}

// 高对比度模式支持
@media (prefers-contrast: high) {
  .server-monitor-container {
    :deep(.el-card) {
      border: 2px solid var(--el-border-color);

      &:hover {
        border-color: var(--el-color-primary);
      }
    }
  }
}

// 减少动画的用户偏好
@media (prefers-reduced-motion: reduce) {
  .server-monitor-container {
    .dashboard-grid {
      animation: none;
    }

    :deep(.el-card) {
      transition: none;

      &:hover {
        transform: none;
      }
    }
  }

  :deep(.el-skeleton__item) {
    animation: none;
  }
}
</style>
